package db

import (
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/config"
	"github.com/beego/beego/v2/core/logs"

	// don't forget this
	_ "github.com/go-sql-driver/mysql"

	"gitee.com/wangxj0826/experiment-codes/service-pressure-test/api"
)

func InitDB() {
	// need to register models in init
	orm.RegisterModel(new(api.User))

	// need to register default database
	dbsource, _ := config.String("dbsource")
	logs.Info("dbsource: %v", dbsource)
	orm.RegisterDataBase("default", "mysql", dbsource)

	// 设置连接数
	orm.SetMaxIdleConns("default", 20)
	orm.SetMaxOpenConns("default", 480)
	// automatically build table
	orm.RunSyncdb("default", false, true)
}

func ReadUserByID(id int64) (*api.User, error) {
	o := orm.NewOrm() // 创建一个 Ormer

	u := &api.User{}
	u.ID = id
	err := o.Read(u)
	return u, err
}

func InsertUser(u *api.User) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(u)
	return id, err
}
